package com.android.lovepick;

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.android.lovepick.map.MapHelper;
import com.android.lovepick.util.BaseUtils;
import com.android.lovepick.util.Constant;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.GeoPoint;
import com.baidu.mapapi.MKDrivingRouteResult;
import com.baidu.mapapi.MKOLUpdateElement;
import com.baidu.mapapi.MKOfflineMap;
import com.baidu.mapapi.MKOfflineMapListener;
import com.baidu.mapapi.MapActivity;
import com.baidu.mapapi.MapView;
import com.baidu.mapapi.RouteOverlay;

/*
 * 地图查询页面只有当用户在发布订单页面选择了推荐路线后才会出现
 */
public class MapViewActivity extends MapActivity
{
	private MainApp mApp = null;
	private MapHelper mMapHelper;
	private RouteOverlay myRouteOverlay = null;
	private RouteOverlay recRouteOverlay = null;
	private MKOfflineMap mOfflineMap = null;

	private static final String MAP_TAG = "MapViewActivity";

	private TextView txvMyOrderGoTime;
	private TextView txvMyOrderSrc;
	private TextView txvMyOrderDest;
	private TextView txvRecOrderGoTime;
	private TextView txvRecOrderSrc;
	private TextView txvRecOrderDest;

	private MapView mMapView;
	private MapHandler mHandler = null;

	private ProgressDialog mProgressDialog;

	private Map<String, String> myOrderMap = null;
	private List<Map<String, String>> mRecOrderList = null;
	private Map<String, String> mRecOrderMap = null;
	private SimpleAdapter mAdapter = null;
	private String[] from = new String[] { "src", "dest", "goTime", "orderID",
			"money", "state" };
	private int[] to = new int[] { R.id.rec_order_list_src,
			R.id.rec_order_list_dest, R.id.rec_order_list_gotime,
			R.id.rec_order_list_orderid, R.id.rec_order_list_money,
			R.id.rec_order_list_state };

	private GeoPoint srcGeo = null;
	private GeoPoint destGeo = null;

	private boolean isSearchingMine = false;

	@Override
	public void onCreate(Bundle bundle)
	{
		super.onCreate(bundle);
		setContentView(R.layout.map);
		findView();

		mHandler = new MapHandler(MapViewActivity.this);

		Log.i(MAP_TAG, "mApp start");
		mApp = (MainApp) this.getApplication();
		Log.i(MAP_TAG, "mApp end");

		if (mApp.bmapMan == null)
		{
			mApp.bmapMan = new BMapManager(getApplication());
			mApp.bmapMan.init(MainApp.key, new MainApp.MyGeneraListener());
		}
		mApp.bmapMan.start();
		super.initMapActivity(mApp.bmapMan);

		Log.i(MAP_TAG, "initMap start");
		initMap();
		initOfflineMap();

		getMyCurrentOrder();
		// getSelectedRecOrder();
	}

	private void findView()
	{
		txvMyOrderGoTime = (TextView) this
				.findViewById(R.id.map_myorder_gotime);
		txvMyOrderSrc = (TextView) this.findViewById(R.id.map_myorder_src);
		txvMyOrderDest = (TextView) this.findViewById(R.id.map_myorder_dest);
		txvRecOrderGoTime = (TextView) this
				.findViewById(R.id.map_rec_order_gotime);
		txvRecOrderSrc = (TextView) this.findViewById(R.id.map_rec_order_src);
		txvRecOrderDest = (TextView) this.findViewById(R.id.map_rec_order_dest);

	}

	private void getMyCurrentOrder()
	{
		// 发布订单页面中, 用户若选择直接推荐路线, 则会保存用户所填写的订单信息;
		// 此处是取出之前保存的用户的订单信息.
		SharedPreferences myCurrentOrderPrefs = getSharedPreferences(
				Constant.PREFS_MY_CURRENT_ORDER, Context.MODE_PRIVATE);
		if (myCurrentOrderPrefs.contains("isRecommend"))
		{
			boolean isRecommend = myCurrentOrderPrefs.getBoolean("isRecommend",
					false);
			if (isRecommend)
			{
				Log.i(MAP_TAG, "get my current order");
				myOrderMap = new HashMap<String, String>();
				myOrderMap.put("src",
						myCurrentOrderPrefs.getString("src", null));
				myOrderMap.put("slat",
						myCurrentOrderPrefs.getString("slat", null));
				myOrderMap.put("slng",
						myCurrentOrderPrefs.getString("slng", null));
				myOrderMap.put("dest",
						myCurrentOrderPrefs.getString("dest", null));
				myOrderMap.put("dlat",
						myCurrentOrderPrefs.getString("dlat", null));
				myOrderMap.put("dlng",
						myCurrentOrderPrefs.getString("dlng", null));
				myOrderMap.put("goTime",
						myCurrentOrderPrefs.getString("goTime", null));
				myOrderMap.put("offset",
						myCurrentOrderPrefs.getString("offset", null));
				myOrderMap.put("money",
						myCurrentOrderPrefs.getString("money", null));

				txvMyOrderSrc.setText(myOrderMap.get("src"));
				txvMyOrderDest.setText(myOrderMap.get("dest"));
				txvMyOrderGoTime.setText(myOrderMap.get("goTime"));
				seachMine();
			}
			else
			{
				BaseUtils.showToast(MapViewActivity.this, "没有我的路线数据!");
			}
		}
	}

	private void getSelectedRecOrder()
	{
		Log.i(MAP_TAG, "get selected recommend order");
		mRecOrderMap = MyOrderActivity.recommendOrder;
		if (mRecOrderMap != null)
		{
			searchRecommend(mRecOrderMap);
		}
	}

	private void initMap()
	{
		mMapView = (MapView) this.findViewById(R.id.map_view);
		mMapView.setBuiltInZoomControls(true);
		mMapView.setDrawOverlayWhenZooming(true);
		myRouteOverlay = new RouteOverlay(MapViewActivity.this, mMapView);
	}

	private void initOfflineMap()
	{
		Log.i(MAP_TAG, "init offline map");
		mOfflineMap = new MKOfflineMap();
		mOfflineMap.init(mApp.bmapMan, new MKOfflineMapListener()
		{

			public void onGetOfflineMapState(int type, int state)
			{
				// TODO Auto-generated method stub
				switch (type)
				{
					case MKOfflineMap.TYPE_DOWNLOAD_UPDATE:
						MKOLUpdateElement update = mOfflineMap
								.getUpdateInfo(state);
						BaseUtils.showToast(MapViewActivity.this, String
								.format("%s:%s", "离线地图有更新!", update.cityName));
						break;

					case MKOfflineMap.TYPE_NEW_OFFLINE:
						Log.i(MAP_TAG,
								String.format("add offline map num:%d", state));
						break;

					case MKOfflineMap.TYPE_VER_UPDATE:
						Log.i(MAP_TAG, "new offline map version");
						break;

					default:
						break;
				}
			}
		});
	}

	private void seachMine()
	{
		Log.i(MAP_TAG, "start searching route...");
		this.isSearchingMine = true;

		this.srcGeo = new GeoPoint((int) ((Double.parseDouble(myOrderMap
				.get("slat")) * 1E6)), (int) ((Double.parseDouble(myOrderMap
				.get("slng")) * 1E6)));
		Log.i(MAP_TAG, "srcGeo: " + srcGeo.toString());

		this.destGeo = new GeoPoint((int) ((Double.parseDouble(myOrderMap
				.get("dlat")) * 1E6)), (int) ((Double.parseDouble(myOrderMap
				.get("dlng")) * 1E6)));
		Log.i(MAP_TAG, "destGeo: " + destGeo.toString());

		mMapHelper = new MapHelper(mApp.bmapMan, mHandler);
		mMapHelper.searchDrivingRoute(srcGeo, destGeo);
		mProgressDialog = ProgressDialog.show(MapViewActivity.this, "搜索我的路线",
				"正在搜索路线", true);
	}

	private void searchRecommend(Map<String, String> map)
	{
		Log.i(MAP_TAG, "---search recommend route---");
		// 移除地图上上一次所显示的推荐路线.
		mMapView.getOverlays().remove(recRouteOverlay);
		Log.i(MAP_TAG, "last recoRouteOverlay removed!");
		recRouteOverlay = null;

		txvRecOrderSrc.setText(map.get("src"));
		txvRecOrderDest.setText(map.get("dest"));
		txvRecOrderGoTime.setText(map.get("goTime"));

		GeoPoint start = new GeoPoint((int) ((Double.parseDouble(((String) map
				.get("slat")))) * 1E6),
				(int) ((Double.parseDouble(((String) map.get("slng")))) * 1E6));
		GeoPoint end = new GeoPoint((int) ((Double.parseDouble(((String) map
				.get("dlat")))) * 1E6),
				(int) ((Double.parseDouble(((String) map.get("dlng")))) * 1E6));
		Log.i(MAP_TAG, "搜索推荐路线");
		mMapHelper.searchDrivingRoute(start, end);
		mProgressDialog = ProgressDialog.show(MapViewActivity.this, "搜索推荐路线",
				"正在搜索路线", true);
	}

	public void viewRecOrders(View view)
	{
		mRecOrderList = MyOrderActivity.recommendOrders;
		if (mRecOrderList != null)
		{
			Log.i(MAP_TAG, "get recommend orders");
			mAdapter = new SimpleAdapter(MapViewActivity.this, mRecOrderList,
					R.layout.rec_order_list, from, to);

			AlertDialog.Builder builder = new AlertDialog.Builder(
					view.getContext());
			builder.setTitle("请选择一条推荐路线");
			builder.setAdapter(mAdapter, new DialogInterface.OnClickListener()
			{
				// 推荐路线中的某一条被选中时, 查询该条线路的驾车路线并在地图上显示.
				public void onClick(DialogInterface dialog, int which)
				{
					// TODO Auto-generated method stub
					if (recRouteOverlay != null)
					{
						Map<String, String> tmp = mRecOrderList.get(which);
						searchRecommend(tmp);
					}
				}
			});
			AlertDialog dialog = builder.create();
			dialog.show();
		}
		else
		{
			BaseUtils.showToast(MapViewActivity.this, "没有推荐路线数据!");
		}
	}

	public void acceptRecOrder(View view)
	{

	}

	private static class MapHandler extends Handler
	{
		private WeakReference<MapViewActivity> mReference;
		private MapViewActivity mActivity;

		public MapHandler(MapViewActivity activity)
		{
			mReference = new WeakReference<MapViewActivity>(activity);
		}

		@Override
		public void handleMessage(Message msg)
		{
			mActivity = mReference.get();

			switch (msg.what)
			{
				case Constant.MSG_DRIVESEARCH_COMPLETE:
					mActivity.mProgressDialog.dismiss();
					MKDrivingRouteResult result = mActivity.mMapHelper
							.getDriveResult();
					if (result == null)
					{
						Toast.makeText(mActivity, "没有搜索到路线...",
								Toast.LENGTH_SHORT).show();
					}
					else
					{
						Toast.makeText(mActivity, "查找到路线...",
								Toast.LENGTH_SHORT).show();
						if (mActivity.isSearchingMine)
						{
							mActivity.myRouteOverlay.setData(result.getPlan(0)
									.getRoute(0));
							mActivity.mMapView.getOverlays().add(
									mActivity.myRouteOverlay);
							Log.i(MAP_TAG, "myRouteOverlay added!");
							mActivity.isSearchingMine = false;
							mActivity.getSelectedRecOrder();
						}

						if (mActivity.recRouteOverlay == null)
						{
							mActivity.recRouteOverlay = new RouteOverlay(
									mActivity, mActivity.mMapView);
							mActivity.recRouteOverlay.setData(result.getPlan(0)
									.getRoute(0));
							mActivity.mMapView.getOverlays().add(
									mActivity.recRouteOverlay);
							Log.i(MAP_TAG, "recoRouteOverlay added...");
							mActivity.mMapView.invalidate();
							mActivity.mMapView.getController().animateTo(
									result.getStart().pt);
						}
					}

					break;

				default:
					mActivity.mProgressDialog.dismiss();
					break;
			}
		}

	}

	@Override
	protected void onPause()
	{
		MainApp app = (MainApp) this.getApplication();
		if (app.bmapMan != null)
		{
			app.bmapMan.stop();
		}
		super.onPause();
	}

	@Override
	protected void onResume()
	{
		MainApp app = (MainApp) this.getApplication();
		app.bmapMan.start();
		super.onResume();
	}

	@Override
	protected boolean isRouteDisplayed()
	{
		// TODO Auto-generated method stub
		return false;
	}
}
